package br.org.credfaz.ficha.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.org.credfaz.ficha.Db2ConnectionFactory;
import br.org.credfaz.ficha.modelo.SaldoDevedor;

public class SaldoDevedorDAO {
	
private final Connection connection;
	
	public SaldoDevedorDAO(){
		try{
			connection = new Db2ConnectionFactory().getConnection();
		}catch (SQLException e){
			throw new RuntimeException(e);
		}
	}
	
	public void adiciona(SaldoDevedor saldodevedor){
		String sql = "update contratocredito set valorsaldodevedor = ?, qtddias = ?, valorsaldodevedorsaida = ?, datasaida = ?, datacadastro = now() where numcontratocredito = ?";
		
		
		PreparedStatement stmt;
		try{
			stmt = connection.prepareStatement(sql);
			
			
			stmt.setFloat(1, saldodevedor.getValorsaldodevedor());
			stmt.setInt(2, saldodevedor.getQtddias());
			stmt.setFloat(3, saldodevedor.getValorsaldodevedorsaida());
			stmt.setDate(4, saldodevedor.getDatasaida());
			stmt.setFloat(5, saldodevedor.getNumcontrato());
			
			
			stmt.execute();
			
		}catch (SQLException e){
			throw new RuntimeException(e);
		}
	}
	
	public void excluiCalculo(float numcontrato) {
		String sql = "update contratocredito set valorsaldodevedor = null, qtddias = null, valorsaldodevedorsaida = null, datasaida = null, datacadastro = null where numcontratocredito = ?";
		PreparedStatement stmt;
		try {
			stmt = connection.prepareStatement(sql);
			stmt.setFloat(1, numcontrato);
			stmt.execute();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<SaldoDevedor> buscaPorContrato(Long idcliente) {
		try {
			
			List<SaldoDevedor> sd = new ArrayList<SaldoDevedor>();
			
			PreparedStatement stmt = this.connection
					.prepareStatement("select * from saldodevedor where idcliente = ? order by numcontrato");
			stmt.setLong(1, idcliente);
			

			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				sd.add(populaSaldodevedor(rs));
			}

			rs.close();
			stmt.close();
			
			
			return sd;
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	
	private SaldoDevedor populaSaldodevedor(ResultSet rs) throws SQLException {

		SaldoDevedor sd = new SaldoDevedor();
		
		sd.setIdcliente(rs.getLong("idcliente"));
		sd.setValorsaldodevedorsaida(rs.getFloat("valorsaldodevedorsaida"));
		sd.setNumcontrato(rs.getFloat("numcontrato"));
		sd.setValorsaldodevedor(rs.getFloat("valorsaldodevedor"));
		sd.setDatasaida(rs.getDate("datasaida"));
		
		
		
		return sd;
	}

}
